package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {


    @Autowired
    SetmealDishService setmealDishService;


    @Override
    @Transactional
    public void saveSetmealWithDish(SetmealDto setmealDto) {

        //保存套餐信息
        this.save(setmealDto);
        Long setmealId = setmealDto.getId();
        //将套餐的id存入setmealDto中
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes = setmealDishes.stream().map(setmealDish -> {
            setmealDish.setSetmealId(setmealId);
            return setmealDish;
        }).collect(Collectors.toList());

        //将套餐和菜品的关联信息 保存到套餐菜品表中  setmeal_dish
        setmealDishService.saveBatch(setmealDishes);
    }


    /**
     * 删除套餐 及套餐菜品表中的信息
     * @param ids
     */
    @Override
    @Transactional
    public void removeWithSetmealDish(List<Long> ids) {

        //先根据id 删除setmeal_dish表中的相关信息
        //条件构造器
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(ids!=null,SetmealDish::getSetmealId,ids);
        setmealDishService.remove(lambdaQueryWrapper);

        //再根据id 删除setmeal中的东西
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper=new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.in(ids!=null,Setmeal::getId,ids);
        this.remove(setmealLambdaQueryWrapper);
    }
}
